package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //更改用户头像
    public void updateHeadPhoto(Long userId, MultipartFile headPhoto) throws IOException {
        //调用阿里云图片识别系统
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //调用图像检测功能
        boolean detect = aipFaceTemplate.detect(url);
        //判断是否识别成功
        if (!detect) {
            //识别不成功
            throw new BusinessException(ErrorResult.faceError());
        }
        // 修改用户头像信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setAvatar(url);
        userInfoApi.update(userInfo);

//        //判断原来的头像是否已经删除
//        UserInfo userInfo = userInfoApi.findById(userId);
//        String avatar = userInfo.getAvatar();
//        if (!StringUtils.isEmpty(avatar)) {
//            throw new BusinessException(ErrorResult.error());
//        }
//        // TODO: 2022/1/7 可以把图片存入缓存 ，再压力减小后从redis调取url存入database
//        //删除成功，将头像存入database
//        UserInfo info = new UserInfo();
//        info.setAvatar(url);
//        // todo 空指针异常，info的id字段为空，无法保存，建议封装userId
//        // todo 向已有userInfo对象中设置头像不应该使用insert方法，建议修改为update方法
//        userInfoApi.save(info);
//        //再次判断userInfo中是否存在照片，
//        if (!StringUtils.isEmpty(avatar)) {
//            throw new RuntimeException("添加成功");
//        }
    }

    /**
     * 校验修改手机的验证码是否正确
     *
     * @param phone
     * @param verificationCode
     */
    public boolean checkVerificationCode(String phone, String verificationCode) {

        //1.校验验证码是否正确
        String key = Constants.SMS_CODE + phone;
        String redisCode = redisTemplate.opsForValue().get(key);

        if (StringUtils.isEmpty(redisCode) || StringUtils.isEmpty(verificationCode) || !verificationCode.equals(redisCode)) {
            return false;
        }else {
            return true;
        }

    }

}
